import React,{Component} from 'react';
import PropTypes from 'prop-types'
import ReactMapboxGl, {Layer, Feature} from 'react-mapbox-gl';


const Map = ReactMapboxGl({
  accessToken: process.env.REACT_APP_MAPBOX_API_TOKEN,
});
const changeMapLanguage = (map) => {
  map.getStyle().layers.forEach((layer) => {
    if (layer.id.endsWith('-label')) {
      map.setLayoutProperty(layer.id, 'text-field', [
        'coalesce',
        ['get', 'name_zh'],
        ['get', 'name'],
      ]);
    }
  });
};


const defaultLocation = { // 默认位置 及 提交时发送的位置
  lat: 23.174778281742533, // 竖
  lng: 113.28594928140097, // 横
  name: '广州市'
}
export default class DisplayMap extends Component{
  static propTypes = {
    location: PropTypes.shape({
      lat: PropTypes.number,
      lng: PropTypes.number,
      name: PropTypes.string,
    }),
    displayOnly: PropTypes.bool,
    onLocationSelect: PropTypes.func,
    zoom: PropTypes.number,
  }
  static defaultProps = {
    displayOnly: true, // 默认显示
    location: defaultLocation,
    onLocationSelect: function () {},
    zoom: 4,
  }
  constructor(props) {
    super(props);
    this.state = {
      location: { // 这里初始化这些的话，是着数无奈之举，应该是第三方库代码的问题，将这两个属性搞错了
        lat: props.location.lng || defaultLocation.lng,
        lng: props.location.lat || defaultLocation.lat,
        name: props.location.name,
      },
      // locationItem: props.location || defaultLocation,
      locations: [], // 选择的位置，可能是多个
      selectedLocation: null, // 确定选择的那个
    };
    this.handleMapOnClick = this.handleMapOnClick.bind(this); // 地图组件被点击


    this.handleLocationUpdate = this.handleLocationUpdate.bind(this); // 当多个位置的其中一个位置被点击时，我们确认了文章的唯一位置
    this.handleSelectLocation = this.handleSelectLocation.bind(this); // 确认某个位置，添加到 state.locations 列表去
    this.resetSearch = this.resetSearch.bind(this);
  }

  componentWillUnmount() {
    this.resetSearch();
  }

  resetSearch(){
    this.setState(() => ({
      locations: [],
      selectedLocation: null
    }))
  }

  handleLocationUpdate(location){
    this.setState(() => {
      return {
        locations: [],
        selectedLocation: location,
      }
    });

    // 调用父组件的方法
    this.props.onLocationSelect(location);
  }


  handleSelectLocation(){
    this.setState(() => ({
      locations: this.state.locations.concat([this.state.location]),
    }))
  }

  handleMapOnClick(event,data){
    let placeNames = event.queryRenderedFeatures(data.point);
    let name = placeNames.map(item => {
      return item.properties.name;
    })[0];
    if (name !== undefined && name !== ''){
      this.setState(() => ({location: {
        lng: data.lngLat.lat,
        lat: data.lngLat.lng,
        // ...data.lngLat,
        name,
      }}));
    }
  }
  render() {
    return [
        <div className="displayMap">
          {this.props.displayOnly ? (<div key="location-typeahead" className="location-typeahead">
            <i className="fa fa-location-arrow"/>
            <input type="button" disabled value={this.state.location.name}/>
            <button
                className="open"
                disabled={this.state.displayOnly}
                onClick={this.handleSelectLocation}
            >
              {this.props.displayOnly && '添加'}
            </button>
          </div>) : null}
          {this.state.locations.length > 0 && this.props.displayOnly ? (
              <div key="location-typeahead-results" className="location-typeahead-results">
                {this.state.locations.map(location => {
                  return (
                      <div
                          onClick={e => {
                            e.preventDefault();
                            this.handleLocationUpdate(location);
                          }}
                          key={location.name}
                          className="result"
                          title="选择该位置"
                      >
                        {location.name}
                      </div>
                  );
                })}
              </div>
          ) : null}

          <Map
              key={`Map-${this.props.id}`}
              onStyleLoad={changeMapLanguage}
              // eslint-disable-next-line
              style="mapbox://styles/mapbox/streets-v11"
              className="map"
              containerStyle={{
                height: '200px',
                width: '100%'
              }}
              center = {[this.state.location.lat,this.state.location.lng]}
              // zoom = {[4]}
              onClick={this.handleMapOnClick}
          >
            <Layer type="symbol" id="marker" layout={{ 'icon-image': 'marker-15' }}>
              <Feature coordinates={[this.state.location.lat,this.state.location.lng]} />
            </Layer>
          </Map>
        </div>,
        <div key="location-description" className="location-description">
              <i className="location-icon fa fa-location-arrow" />
              <span className="location-name">{this.state.location.name}</span>
        </div>
    ]
  }
}
